﻿using FolderTag.DB;
using FolderTag.Model;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using SQLBuilder.Core.Extensions;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace FolderTag.FolderView
{
    /// <summary>
    /// QuickPathManage.xaml 的交互逻辑
    /// </summary>
    public partial class QuickPathManage : UserControl
    {
        MainWindow _MainWindow;

        public QuickPathManage()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            _MainWindow = this.TryFindParent<MainWindow>();
            LoadQuickPath();
        }

        private void Button_AddQuick_Click(object sender, RoutedEventArgs e)
        {
            string path = _MainWindow.Ctl_FolderControl.ParentPath_TextBox.Text;
            if (string.IsNullOrEmpty(path))
                _MainWindow.ShowModalMessageExternal("添加失败", "不能将计算机根目录作为快速访问", MessageDialogStyle.Affirmative, _MainWindow.MetroDialogSettings);
            else
            {
                if (!"\\".Equals(path.Substring(path.Length - 1, 1)))
                    path = $"{path}\\";
                QuickPathItem addItem = new QuickPathItem()
                {
                    Path = path
                };
                QuickPathDb.Add(addItem);
                LoadQuickPath(true);
            }
        }

        private void Button_QucikPath_Click(object sender, RoutedEventArgs e)
        {
            QuickPathItem quickItem = ((sender as Button).Parent as Grid).DataContext as QuickPathItem;
            if (quickItem != null)
            {
                _MainWindow.Ctl_FolderControl.LoadPath(quickItem.Path);
            }
        }

        /// <summary>
        /// 加载标签
        /// </summary>
        public void LoadQuickPath(bool isRefresh = false)
        {
            var dataList = QuickPathDb.QueryList(isRefresh);
            QuickPath_ListBox.ItemsSource = dataList;
            QuickPath_ListBox_NoData.Visibility = dataList.Count() > 0 ? Visibility.Collapsed : Visibility.Visible;
        }

        private void Button_DelQuickPath_Click(object sender, RoutedEventArgs e)
        {
            QuickPathItem quickItem = ((sender as Button).Parent as Grid).DataContext as QuickPathItem;
            if (quickItem != null)
            {
                var mesResult = _MainWindow.ShowModalMessageExternal("删除快速访问", $"是否删除快速访问[{quickItem.Path}]", MessageDialogStyle.AffirmativeAndNegative, _MainWindow.MetroDialogSettings);
                if (mesResult == MessageDialogResult.Affirmative)
                {
                    QuickPathDb.Delete(quickItem.Id);
                    LoadQuickPath(true);
                }
            }
        }
    }
}
